<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

// 查询参数
const timeType = ref('小时')
const trafficType = ref('总流量')
const operator = ref('ALL')
const networkType = ref('ALL')

const dateMinusDay = (date, days) => {
  const d = new Date(date)
  d.setDate(d.getDate() - days)
  return d
}
const lastWeek = dateMinusDay(new Date(), 7)
// 添加日期范围ref
const dateRange = ref({ start: lastWeek, end: new Date() })

// 下拉选项
const timeTypeOptions = ['小时', '天', '月']

const trafficTypeOptions = ['总流量', '上行流量', '下行流量']

const operatorOptions = ['ALL', 'CMCC', 'CTCC', 'CUCC']

const networkTypeOptions = ['ALL', '4G', '3G', '2G']

// 提交查询
const submitQuery = () => {
  fetchChartData()
}

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const fetchChartData = async () => {
  try {
    const params = {
      dateRange: dateRange.value,
      timeType: timeType.value,
      trafficType: trafficType.value,
      operator: operator.value,
      networkType: networkType.value,
    }

    const response = await axios.get('/api/phone/flow-rank', { })
    const { dimensions, source } = response.data.data

    if (!chart || !chartRef.value) return

    const option: echarts.EChartsOption = {
      legend: {},
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      dataset: {
        dimensions: dimensions,
        source: source
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '流量 (GB)'
      },
      series: [
        {
          type: 'bar',
          name: '总流量'
        },
        {
          type: 'bar',
          name: 'Wi-Fi'
        },
        {
          type: 'bar',
          name: '移动数据'
        }
      ]
    }

    chart.setOption(option)
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 添加新的 ref 和图表实例
const pieChartRef = ref<HTMLElement | null>(null)
let pieChart: echarts.ECharts | null = null

// 添加饼图数据获取函数
const fetchPieData = async () => {
  try {
    const params = {
      dateRange: dateRange.value,
      timeType: timeType.value,
      trafficType: trafficType.value,
      operator: operator.value,
      networkType: networkType.value,
    }

    const response = await axios.get('/api/phone/flow-pie', {})
    const { pieData } = response.data.data

    if (!pieChart || !pieChartRef.value) return

    const option: echarts.EChartsOption = {
      title: {
        text: '热门手机排名',
        subtext: '流量占比',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '50%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }

    pieChart.setOption(option)
  } catch (error) {
    console.error('获取饼图数据失败:', error)
  }
}

// 修改初始化函数
const initCharts = () => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    fetchChartData()
  }
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value)
    fetchPieData()
  }
}

onMounted(() => {
  initCharts()
  window.addEventListener('resize', () => {
    chart?.resize()
    pieChart?.resize()
  })
})

// 修改监听函数
watch([dateRange, timeType, trafficType, operator, networkType], () => {
  fetchChartData()
  fetchPieData()
})
</script>

<template>
  <VaCard>
    <VaCardContent>
      <div class="flex flex-col justify-between gap-2 mb-4 md:flex-row">
        <div class="flex flex-col justify-start gap-2 md:flex-row">
          <VaDateInput v-model="dateRange" mode="range" label="日期范围" placeholder="日期范围" />
          <VaSelect v-model="timeType" :options="timeTypeOptions" label="时间粒度" placeholder="时间粒度" />
          <VaSelect v-model="trafficType" :options="trafficTypeOptions" label="流量类型" placeholder="流量类型" />
          <VaSelect v-model="operator" :options="operatorOptions" label="运营商" placeholder="运营商" />
          <VaSelect v-model="networkType" :options="networkTypeOptions" label="网络类型" placeholder="网络类型" />
        </div>
        <div class="flex gap-2">
          <VaButton @click="submitQuery">查询</VaButton>
        </div>
      </div>
      <!-- 图表容器使用网格布局 -->
      <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
        <!-- 柱状图容器 -->
        <div ref="chartRef" style="width: 100%; height: calc(100vh - 245px)"></div>
        <!-- 饼图容器 -->
        <div ref="pieChartRef" style="width: 100%; height: calc(100vh - 245px)"></div>
      </div>
    </VaCardContent>
  </VaCard>
</template>

<style>
.va-date-input {
  width: 200px;
}
.va-select {
  width: 180px;
}
.va-button {
  margin-top: 16px;
  height: 35px;
  width: 80px;
}
</style>
